const WebSocket = require('ws');

// 创建 WebSocket 服务器，监听 3000 端口
const wss = new WebSocket.Server({ port: 3000 });

function getNowFormatDate() {
    let currentDate = new Date();
    let year = currentDate.getFullYear();  // 获取年份
    let month = currentDate.getMonth() + 1;  // 获取月份 (0-11，所以需要加1)
    let date = currentDate.getDate();  // 获取日期
    let hours = currentDate.getHours();  // 获取小时
    let minutes = currentDate.getMinutes();  // 获取分钟
    let seconds = currentDate.getSeconds();  // 获取秒数
    let time = year + '-' + month + '-' + date +'' + hours + ':' + minutes + ':' + seconds;
    return time;
}
console.log('WebSocket 服务器已启动，监听端口 3000...');

// 广播消息给所有已连接的客户端
function broadcast(message, sender,date) {
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN && client !== sender) {
      client.send(message,date);
    }
  });
}

// 监听客户端连接
wss.on('connection', (ws) => {
  console.log('新客户端已连接'+getNowFormatDate());

  // 向新客户端发送欢迎消息
  ws.send('欢迎加入聊天室！'+getNowFormatDate());

  // 监听客户端发送的消息
  ws.on('message', (message,date) => {
    console.log(`收到消息: ${message} ${date}`);
    broadcast(message, ws); // 转发消息给其他客户端
  });

  // 监听客户端断开连接
  ws.on('close', () => {
    console.log('客户端已断开连接'+getNowFormatDate());
  });

  // 监听错误
  ws.on('error', (err) => {
    console.error('WebSocket 错误:', err+getNowFormatDate());
  });
});
